<?php

require_once 'Zend/Controller/Action/Helper/Abstract.php';
require_once 'Core/User.php';

/**
 * This controller plugin is used to bootstrap the crontab user should you ever
 * want to access the application stack from the commandline for example, with cron).
 * It will construct the crontab user and give it the 'cron' user group, so that
 * you can carefully control what the crontab user is allowed to manipulate using
 * the standard ACL configuration mechanism.
 * 
 * @author Michael Krotscheck
 *
 */
class Core_Controller_Plugin_Cron extends Zend_Controller_Plugin_Abstract
{
	/**
	 * Constructor
	 *
	 * @return void
	 */
	function __construct ()
	{
	}

	/**
	 * CLI Initialization helper. This sets up a session and
	 * creates a user with "CLI" level access.
	 */
	public function dispatchLoopStartup($request)
	{
		$cli_user = Core_User::factory('crontab@fancybrandname.com');
	
		if ( empty($cli_user) )
		{
			$cli_user = Core_User::factory();
			$cli_user->email = 'crontab'; // We're not adding an email address here.
			$cli_user->firstName = 'Crontab';
			$cli_user->lastName = 'Crontab';
			$cli_user->validated = 1;
			$cli_user->password = sha1(date(DateTime::ATOM) . mt_rand(0, 100000000000));
			$cli_user->role = Core_User::ROLE_CRON;
			$cli_user->save();
		}
		
		// First, let's shuffle the password for good measure
		$cli_user->password = sha1(date(DateTime::ATOM) . mt_rand(0, 100000000000));
		$cli_user->save();
		
		// Now create the identity and the session
		Zend_Auth::getInstance()->getStorage()->write($cli_user->email);
		Core_User::setCurrentUser($cli_user);
	}

	/**
	 * CLI Shutdown helper. This kills our session
	 */
	public function dispatchLoopShutdown()
	{
		// Retrieve necessary models
		Core_User::setCurrentUser(null);
		Zend_Auth::getInstance()->clearIdentity();
	}
}